<template>
	<view class="friend-search-page">
		<view class="search-bar-container" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="search-input-wrapper">
				<u-icon name="search" color="#B2B2B2" size="18"></u-icon>
				<input
					class="search-input"
					type="text"
					v-model="keyword"
					placeholder="搜索手机号"
					confirm-type="search"
					@input="handleInput"
					@confirm="triggerSearch"
					:focus="isInputFocused"
					@focus="isInputFocused = true"
					@blur="isInputFocused = false"
				/>
				<u-icon
					v-if="keyword.length > 0"
					name="close-circle-fill"
					color="#C8C9CC"
					size="18"
					@click="clearKeyword"
				></u-icon>
			</view>
			<text class="cancel-button" @click="navigateBack">取消</text>
		</view>

		<view class="search-content" :style="{ paddingTop: searchBarTotalHeight + 'px' }">
			<view v-if="keyword.length > 0 && !isLoading && !userFound && !noUserFound" class="search-trigger-item" @click="triggerSearch">
				<view class="search-trigger-icon-bg">
					<u-icon name="plus-people-fill" color="#ffffff" size="24"></u-icon>
				</view>
				<text class="search-trigger-text">搜索: {{ keyword }}</text>
			</view>

			<view v-if="isLoading" class="loading-container">
				<u-loading-icon mode="circle" size="28"></u-loading-icon>
				<text>正在搜索...</text>
			</view>

			<view v-if="userFound && foundUser" class="user-found-item" @click="navigateToUserProfile(foundUser.userId)">
				<u-avatar :src="foundUser.avatar" size="40"  mode="aspectFill"></u-avatar>
				<text class="user-name">{{ foundUser.nickName || foundUser.userName }}</text>
			</view>

			<view v-if="noUserFound" class="no-user-found">
				<u-empty mode="search" text="该用户不存在"></u-empty>
			</view>
		</view>
	</view>
</template>

<script>
import { getClientUserList } from '@/request/api.js';

export default {
	data() {
		return {
			keyword: '',
			isInputFocused: false,
			isLoading: false,
			userFound: false,
			foundUser: null,
			noUserFound: false,
			statusBarHeight: 0,
			searchBarHeight: 44, // 导航栏内容区域标准高度
		};
	},
	computed: {
		searchBarTotalHeight() {
			return this.statusBarHeight + this.searchBarHeight;
		}
	},
	onLoad() {
		const systemInfo = uni.getSystemInfoSync();
		this.statusBarHeight = systemInfo.statusBarHeight || 0;
	},
	onShow() {
		// 确保每次进入页面输入框都聚焦
		setTimeout(() => {
			this.isInputFocused = true;
		}, 150);
	},
	methods: {
		handleInput() {
			// 当用户输入时，重置搜索状态，只显示“搜索：xxx”
			this.userFound = false;
			this.foundUser = null;
			this.noUserFound = false;
			this.isLoading = false;
		},
		clearKeyword() {
			this.keyword = '';
			this.handleInput(); // 触发状态重置
		},
		navigateBack() {
			uni.navigateBack();
		},
		async triggerSearch() {
			if (!this.keyword.trim()) {
				uni.showToast({ title: '请输入搜索内容', icon: 'none' });
				return;
			}
			this.isLoading = true;
			this.userFound = false;
			this.foundUser = null;
			this.noUserFound = false;

			try {
				// 尝试使用不同参数搜索，后端API应能处理模糊匹配
				// 后端理想情况是接收一个通用 keyword，然后在多个字段（userName, nickName, phonenumber, email）中查找
				const params = {
					// userName: this.keyword, // 可以尝试
					// nickName: this.keyword, // 可以尝试
					phonenumber: /^\d+$/.test(this.keyword) ? this.keyword : undefined, // 如果是纯数字，尝试作为手机号
					email: this.keyword.includes('@') ? this.keyword : undefined, // 如果包含@，尝试作为邮箱
					keyword: this.keyword, // 通用关键词，让后端判断
					pageNum: 1,
					pageSize: 1 // 我们只需要找到一个或确认不存在
				};
				// 清理 undefined 参数
				Object.keys(params).forEach(key => params[key] === undefined && delete params[key]);


				const res = await getClientUserList(params);
				if (res.data && res.data.code === 200) {
					if (res.data.rows && res.data.rows.length == 1) {
						this.foundUser = res.data.rows[0]; // 取第一个匹配的用户
						// this.userFound = true;
						// 如果直接跳转到用户主页
						this.navigateToUserProfile(this.foundUser.userId);
					} else {
						this.noUserFound = true;
					}
				} else {
					this.noUserFound = true;
					uni.showToast({ title: res.data.msg || '搜索失败', icon: 'none' });
				}
			} catch (error) {
				console.error('搜索用户失败:', error);
				this.noUserFound = true;
				uni.showToast({ title: '搜索请求异常', icon: 'none' });
			} finally {
				this.isLoading = false;
			}
		},
		navigateToUserProfile(userId) {
			uni.navigateTo({
				url: `/pages_sub/user/others/others?userId=${userId}`,
			});
		},
	},
};
</script>

<style lang="scss" scoped>
.friend-search-page {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f8f8f8; // 与图片背景色相似
}

.search-bar-container {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	display: flex;
	align-items: center;
	height: 44px; // 与标准导航栏内容区同高
	padding: 0 24rpx;
	background-color: #f8f8f8;
	border-bottom: 1rpx solid #e8e8e8;
	z-index: 100;

	.search-input-wrapper {
		flex-grow: 1;
		display: flex;
		align-items: center;
		background-color: #ffffff; // 输入框背景白色
		border-radius: 8rpx;     // 轻微圆角
		padding: 0 16rpx;
		height: 64rpx;           // 输入框高度

		.search-input {
			flex-grow: 1;
			height: 100%;
			padding: 0 12rpx;
			font-size: 28rpx;
			color: #303133;
		}
	}

	.cancel-button {
		margin-left: 24rpx;
		font-size: 30rpx;
		color: #303133; // 微信取消按钮颜色
		white-space: nowrap;
	}
}

.search-content {
	flex-grow: 1;
	padding-top: 88rpx; // 预留给固定搜索栏的空间 (statusBarHeight + searchBarHeight)
	background-color: #f8f8f8;
}

.search-trigger-item {
	display: flex;
	align-items: center;
	padding: 24rpx 30rpx;
	background-color: #ffffff; // 搜索触发项背景白色
	border-bottom: 1rpx solid #f0f0f0;
	.search-trigger-icon-bg {
		width: 72rpx;
		height: 72rpx;
		border-radius: 8rpx;
		background-color: #07C160; // 微信绿色
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 24rpx;
	}
	.search-trigger-text {
		font-size: 30rpx;
		color: #07C160; // 微信绿色
		font-weight: 500;
	}
}

.loading-container {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 40rpx;
	color: #909399;
	font-size: 28rpx;
	text {
		margin-left: 10rpx;
	}
}

.user-found-item {
	display: flex;
	align-items: center;
	padding: 20rpx 30rpx;
	background-color: #ffffff;
	border-bottom: 1rpx solid #f0f0f0;
	.user-name {
		font-size: 30rpx;
		color: #303133;
		margin-left: 20rpx;
	}
}

.no-user-found {
	padding-top: 100rpx; // 给一些上边距
}
</style>